<template>
  <div class="home-container">
    <van-nav-bar
      title="黑马头条"
      fixed
    />
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleInfo
          v-for="item in artlist"
          :key="item.id"
          :title="item.title"
          :author="item.aut_name"
          :comnum="item.comm_count"
          :pubdate="item.pubdate"
          :cover="item.cover"
        ></ArticleInfo>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleListAPI } from '@/api/articleAPI.js'
import ArticleInfo from '@/components/Article/ArticleInfo.vue'

export default {
  name: 'home',
  data() {
    return {
      page: 1,
      limit: 10,
      artlist: [],
      // 是否正在加载数据 防止用户下拉刷新时反复触发 load 事件
      loading: true,
      // 所有数据是否加载完毕
      finished: false,
      // 是否正在下拉刷新
      refreshing: true
    }
  },
  methods: {
    async initArticleList(isRefresh) {
      const { data: res } = await getArticleListAPI(this.page, this.limit)
      // 判断是否为下拉刷新 下拉刷新时重置数据
      if (isRefresh) this.artlist = []
      this.artlist = [...this.artlist, ...res]
      this.loading = false
      this.refreshing = false
      // 当所有数据请求完的时候 finished变为true
      if (res.length === 0) this.finished = true
    },
    onLoad() {
      this.page++
      this.initArticleList()
    },
    onRefresh() {
      this.page = 1
      this.initArticleList(true)
    }
  },
  created() {
    this.initArticleList()
  },
  components: {
    ArticleInfo
  }
}
</script>

<style lang="less" scoped>
.home-container {
  padding: 46px 0 50px 0;
  .van-nav-bar {
    /deep/ .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>